package com.otitan.la.forest.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.otitan.la.forest.system.dto.RoleDTO;
import com.otitan.la.forest.system.entity.MenuRoleEntity;
import com.otitan.la.forest.system.entity.PermissionRoleEntity;
import com.otitan.la.forest.system.entity.RoleEntity;
import com.otitan.la.forest.system.entity.UserRoleEntity;
import com.otitan.la.forest.system.mapper.RoleMapper;
import com.otitan.la.forest.system.service.MenuRoleService;
import com.otitan.la.forest.system.service.PermissionRoleService;
import com.otitan.la.forest.system.service.RoleService;
import com.otitan.la.forest.system.service.UserRoleService;
import com.otitan.la.forest.system.vo.RoleVO;
import com.otitan.webapp.framework.basepro.exception.code.BaseResponseCode;
import com.otitan.webapp.framework.basepro.model.DataResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import java.util.List;

@Slf4j
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleEntity> implements RoleService {

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private MenuRoleService menuRoleService;
    @Autowired
    private PermissionRoleService permissionRoleService;

    @Override
    public DataResult add(RoleEntity role, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        // 角色编码不能重复
        // 角色名不能重复
        LambdaQueryWrapper<RoleEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(RoleEntity::getCode, role.getCode())
                .or().eq(RoleEntity::getName, role.getName());
        int count = this.count(queryWrapper);
        if (count > 0) {
            return DataResult.fail("名称或者编码已存在");
        }
        boolean isSuccess = this.save(role);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
    }

    @Override
    public DataResult batchDelete(List<String> ids) {
        LambdaQueryWrapper<UserRoleEntity> userRoleWrapper = Wrappers.lambdaQuery();
        userRoleWrapper.in(UserRoleEntity::getRoleId, ids);
        int count = userRoleService.count(userRoleWrapper);
        if (count > 0) {
            return DataResult.fail("该角色已关联用户，请先取消用户与该角色的关联或删除用户");
        }
        // 删除菜单角色
        LambdaQueryWrapper<MenuRoleEntity> menuRoleWrapper = Wrappers.lambdaQuery();
        menuRoleWrapper.in(MenuRoleEntity::getRoleId, ids);
        menuRoleService.remove(menuRoleWrapper);

        // 删除按钮角色
        LambdaQueryWrapper<PermissionRoleEntity> permissionRoleWrapper = Wrappers.lambdaQuery();
        permissionRoleWrapper.in(PermissionRoleEntity::getRoleId, ids);
        permissionRoleService.remove(permissionRoleWrapper);

        boolean isSuccess = this.removeByIds(ids);
        log.debug("\n>>>>>>>>> 【删除角色表】 <<<<<<<<<\n操作结果：{}，ids：{}\n>>>>>>>>> ---- <<<<<<<<<", isSuccess, ids);
        return DataResult.success();
    }

    @Override
    public DataResult editor(RoleEntity role, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return DataResult.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        // 角色编码不能重复
        // 角色名不能重复
        LambdaQueryWrapper<RoleEntity> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.and(w ->
                w.ne(RoleEntity::getId, role.getId()).eq(RoleEntity::getCode, role.getCode())
        ).and(w ->
                w.ne(RoleEntity::getId, role.getId()).eq(RoleEntity::getName, role.getName())
        );
        int count = this.count(queryWrapper);
        if (count > 0) {
            return DataResult.fail("名称或者编码已存在");
        }
        boolean isSuccess = this.updateById(role);
        return isSuccess ? DataResult.success() : DataResult.fail(BaseResponseCode.DATA_NOT_EXIST.getMsg());
    }

    @Override
    public DataResult findPageData(long page, long size, RoleDTO role) {
        Page<RoleVO> pagePlug = new Page<>(page, size);
        pagePlug.setRecords(baseMapper.findPageData(role, pagePlug));
        return DataResult.success(pagePlug);
    }

    @Override
    public DataResult findOne(String id) {
        return DataResult.success(this.getById(id));
    }

}